<template>
  <div>
    <!-- 上面的按钮 -->
    <div class="bot">
      <el-button
        style="margin-right: 30px; margin-bottom: 20px; width: 100px"
        type="primary"
        size="small"
        icon="el-icon-trophy"
        @click="showAdd"
        >新增赛事</el-button
      >
    </div>
    <!-- 中间的表格 -->
    <div>
      <el-table
        class="form"
        :data="tableData"
        style="
          width: 100%;

          background: #ffffff;
          border-radius: 8px;
        "
        :header-cell-style="{
          background: 'rgba(61,157,255,0.05)',
          color: '#333333',
        }"
      >
        <el-table-column prop="matchName" label="赛事名称" align="center">
        </el-table-column>
        <el-table-column prop="matchCode" label="子项目" align="center">
        </el-table-column>
        <el-table-column prop="matchBeginTime" label="启动时间" align="center">
          <!-- <template slot-scope="scope">
            {{ scope.row.status == 0 ? "未启用" : "已启用" }}
          </template> -->
        </el-table-column>
        <el-table-column prop="status" label="当前状态" align="center">
          <template slot-scope="scope">
            {{ getSource(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="赛制" align="center">
          <template slot-scope="scope">
            {{
              (scope.row.matchScoreType == 1 ? "积分赛" : "巅峰赛") +
              " - " +
              (scope.row.matchType == 1 ? "个人赛" : "班级赛")
            }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" align="center" width="160px">
          <template slot-scope="scope">
            <el-button
              type="info"
              plain
              size="small"
              style="width: 50%"
              v-if="scope.row.status == 2"
              :disabled="scope.row.status == 2"
              @click="updataStatus($event, scope.row)"
              >终止</el-button
            >

            <el-button
              type="danger"
              plain
              size="small"
              v-if="scope.row.status == 1"
              @click="updataStatus($event, scope.row)"
              >进行中</el-button
            >
            <el-button
              plain
              size="small"
              v-if="scope.row.status == 0"
              @click="updataStatus($event, scope.row)"
              >未开始
            </el-button>

            <el-button
              size="small"
              plain
              type="primary"
              @click="gradeEdit(scope.row.matchId)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 下面的分页器 -->

      <!-- <pagination-page @size="changeSize" @page="changePage" :total="total" /> -->
    </div>

    <!-- 遮罩层 -->
    <div>
      <el-dialog
        :title="title"
        :visible.sync="dialogFormVisible"
        class="bott"
        width="800px"
        :close-on-click-modal="false"
      >
        <el-form :model="form" :rules="rules" ref="ruleForm">
          <!-- 赛事名称 -->
          <div>
            <el-form-item
              label="赛事名称"
              :label-width="formLabelWidth"
              prop="matchName"
            >
              <el-input
                style="width: 100%"
                maxlength="10"
                v-model="form.matchName"
                autocomplete="off"
                placeholder="单行输入"
                :disabled="forbiddenshow"
              ></el-input>
            </el-form-item>
          </div>

          <el-form-item
            label="选择项目"
            :label-width="formLabelWidth"
            prop="matchName"
          >
            <!-- 内容 -->
            <div class="topsss">
              <el-form-item label="内容" prop="matchSport">
                <el-select
                  style="width: 85%"
                  :disabled="forbiddenshow"
                  clearable
                  v-model="form.matchSport"
                  placeholder="请选择内容"
                >
                  <el-option value="1" :label="'体育运动'"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="分类" prop="classificationCode">
                <el-select
                  :disabled="forbiddenshow"
                  clearable
                  @change="forbiddenshowcodes"
                  v-model="form.classificationCode"
                  placeholder="请选择分类"
                >
                  <el-option
                    v-for="item in exercise"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="子项目" prop="matchCode">
                <el-select
                  clearable
                  style="width: 100%"
                  :disabled="forbiddenshowcode"
                  v-model="form.matchCode"
                  placeholder="请选择子项目"
                >
                  <template v-if="classificationCode">
                    <el-option
                      v-for="item in exercise.filter(
                        (item) => item.code == classificationCode
                      )[0].children"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </div>
          </el-form-item>
          <!-- 中间 -->
          <div class="tvs">
            <!-- 启动时间 -->
            <el-form-item
              label="启动时间"
              :label-width="formLabelWidth"
              prop="beganTime"
            >
              <el-date-picker
                style="width: 100%"
                :disabled="forbiddenshow"
                v-model="form.beganTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item
              label="比赛时间"
              :label-width="formLabelWidth"
              prop="time"
            >
              <el-date-picker
                :disabled="forbiddenshow"
                @change="getTiem"
                v-model="form.time"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </div>
          <!-- 比赛形式 -->
          <el-form-item
            label="比赛形式"
            :label-width="formLabelWidth"
            prop="matchType"
          >
            <el-row>
              <el-col :span="14">
                <el-radio-group
                  v-model="form.matchScoreType"
                  size="small"
                  :disabled="forbiddenshow"
                  @change="buttons"
                >
                  <div class="seo">
                    <div class="topss">
                      <el-radio-button label="1" value="1"
                        >积分赛</el-radio-button
                      >
                      <el-radio-button label="2" value="2"
                        >巅峰赛</el-radio-button
                      >
                    </div>
                  </div>
                </el-radio-group>
                <el-radio-group
                  v-model="form.matchType"
                  size="small"
                  :disabled="forbiddenshow"
                >
                  <div class="seoo">
                    <div class="topss">
                      <span class="wenzi">参赛形式：</span>

                      <el-radio-button label="1" value="1"
                        >个人</el-radio-button
                      >
                      <el-radio-button label="2" value="2" v-if="buttonShow"
                        >班级</el-radio-button
                      >
                    </div>
                  </div>
                </el-radio-group>
              </el-col>
              <el-col :span="10">
                <el-form-item
                  label="适用年级"
                  :label-width="formLabelWidth"
                  prop="gradeId"
                >
                  <el-select
                    :disabled="forbiddenshow"
                    style="width: 100%"
                    clearable
                    v-model="form.gradeId"
                    placeholder="请选择适用年级"
                  >
                    <el-option
                      v-for="(item, index) in gradeSource"
                      :value="item.gradeId"
                      :label="item.gradeName"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <div>
            <el-form-item
              label="赛事封面"
              :label-width="formLabelWidth"
              prop="coverImage"
              style="width: 100%"
            >
              <el-upload
                class="upload-demo"
                drag
                v-loading="loading"
                :on-success="coverImageUpload"
                :before-upload="beforeUpload"
                :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
                multiple
                :headers="{
                  'access-token': $store.state.user.TOKEN,
                }"
              >
                <div v-if="!form.coverImage">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                </div>
                <img
                  style="
                    width: auto;
                    height: auto;
                    max-height: 100%;
                    max-width: 100%;
                  "
                  v-if="form.coverImage"
                  :src="$store.state.user.BASE_URL + form.coverImage"
                  alt=""
                />
                <div class="el-upload__tip" slot="tip">
                  只能上传jpg/png文件，建议不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </div>
        </el-form>
        <!-- 按钮 -->
        <div slot="footer" class="dialog-footer" v-if="footerShow">
          <el-button size="small" @click="dialogFormVisible = false">
            取 消
          </el-button>
          <el-button size="small" type="primary" @click="add">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getStuHealthLogList,
  getsportevent,
  getneweventsadded,
  getterminationofrace,
  getterminationofracess,
} from "@/api/sportsevent/index";
import { gradeList } from "@/api/school/grade";
export default {
  data() {
    return {
      forbiddenshow: false,
      title: "新增赛事",
      loading: false,
      classificationCode: "",
      forbiddenshowcode: true,
      footerShow: true,
      buttonShow: true,
      value1: "",
      value11: "",
      total: -1,
      page: {
        pageSize: 10,
        pageNum: 1,
      },
      tableData: [],
      exercise: [],
      getsportevent: [],
      dialogFormVisible: false,
      form: {
        matchScoreType: "",
        matchCodeName: "",
        matchName: "",
        matchSport: "",
        matchCode: "",
        matchType: "",
        matchBeginTime: "",
        matchEndTime: "",
        matchId: "",
        gradeId: "",
        beganTime: "",
        classificationCode: "",
        time: "",
        coverImage: "",
      },
      gradeSource: [],
      formLabelWidth: "120px",
      data: [],
      time: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      sportClassIfy: "",
      // 校验
      rules: {
        matchName: [
          {
            required: true,
            message: "请输入赛事名称",
            trigger: "blur",
          },
        ],
        gradeId: [
          {
            required: true,
            message: "请输入适用年级",
            trigger: "blur",
          },
        ],
        matchSport: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
        classificationCode: [
          {
            required: true,
            message: "请输入分类",
            trigger: "blur",
          },
        ],
        matchCode: [
          {
            required: true,
            message: "请输入子项目",
            trigger: "blur",
          },
        ],
        beganTime: [
          {
            required: true,
            message: "请输入启动时间",
            trigger: "blur",
          },
        ],
        matchType: [
          {
            required: true,
            message: "请点击比赛形式",
            trigger: "blur",
          },
        ],
        time: [
          {
            required: true,
            message: "请输入开始日期和结束日期",
            trigger: "blur",
          },
        ],
        coverImage: [
          {
            required: true,
            message: "请上传封面",
          },
        ],
      },
    };
  },
  created() {
    this.getsportseventlist();
    this.getgetneweventsaddedlist();
    this.getGradeList();
  },
  watch: {
    sportClassIfy: {
      immediate: true,
      handler() {
        this.form.matchCode = "";
      },
    },
  },
  methods: {
    getSource(val) {
      if (val == 0) {
        return "未启用";
      } else if (val == 1) {
        return "已启用";
      } else if (val == 2) {
        return "已结束";
      }
    },
    beforeUpload(file) {
      this.loading = true;
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
        this.loading = false;
      }
      return types.includes(fileSuffix);
    },
    coverImageUpload(e) {
      if (e.code === 200) {
        this.form.coverImage = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.$refs.ruleForm.validate(() => {});
      this.loading = false;
    },
    buttons(val) {
      console.log("______", val);
      if (val == 1) {
        this.buttonShow = true;
      } else {
        this.buttonShow = false;
      }
    },
    forbiddenshowcodes(value) {
      this.forbiddenshowcode = false;
      this.form.matchCode = "";
      this.classificationCode = value;
    },
    gradeEdit(val) {
      this.title = "赛事详情 ";
      let obj = {
        matchId: val,
      };
      getterminationofracess(obj).then((res) => {
        this.classificationCode = res.result.matchIdF;
        if (res.result.status == 1 || res.result.status == 2) {
          this.footerShow = false;
          this.forbiddenshow = true;
          this.forbiddenshowcode = true;
        } else {
          this.buttonShow = false;
          this.footerShow = true;
          this.forbiddenshow = false;
          this.forbiddenshowcode = false;
        }

        this.form = { ...res.result };
        this.form.classificationCode = res.result.matchIdF;

        this.$set(this.form, "time", [
          res.result.matchBeginTime,
          res.result.matchEndTime,
        ]);
        this.dialogFormVisible = true;
      });
    },
    getGradeList() {
      gradeList({ schoolId: this.$store.state.user.USER_INFO.pscShId }).then(
        (response) => {
          if (response.code === 200) {
            this.gradeSource = response.result;
          }
        }
      );
    },
    handleNodeClick(data) {},
    // 获取表格赛事列表
    getsportseventlist() {
      let data = {
        schoolId: this.$store.state.user.USER_INFO.schoolId,
        ...this.page,
        status: '',
        dateStatus: '',
        startTime:'',
        endTime:'',
      };
      getStuHealthLogList(data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.result;
          this.total = res.result.total;
        }
      });
    },
    // 获取运动项目
    getgetneweventsaddedlist() {
      getsportevent({}).then((res) => {
        if (res.code == 200) {
          this.exercise = res.result;
        }
      });
    },
    // 添加赛事
    showAdd() {
      this.buttonShow = true;
      this.forbiddenshow = false;
      this.forbiddenshowcode = true;
      this.footerShow = true;
      this.title = "新增赛事";
      this.form = {
        matchScoreType: "",
        matchName: "",
        matchSport: "",
        coverImage: "",
        matchCode: "",
        matchType: "",
        matchBeginTime: "",
        matchEndTime: "",
        matchId: "",
        gradeId: "",
        beganTime: "",
        classificationCode: "",
        time: "",
      };
      this.time = [];
      this.classificationCode = "";
      this.sportClassIfy = "";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    //确定保存
    add() {
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          let data = {
            ...this.form,
          };
          if (
            Date.parse(new Date(this.form.beganTime)) >=
              Date.parse(new Date(this.form.matchBeginTime)) &&
            Date.parse(new Date(this.form.beganTime)) <=
              Date.parse(new Date(this.form.matchEndTime))
          ) {
            getneweventsadded(data).then((res) => {
              if (res.code == 200) {
                this.dialogFormVisible = false;
                this.$message.success("成功!");
                this.getsportseventlist();
              } else {
                this.$message.error(res.message);
              }
            });
          } else {
            this.$message.error("启动时间必须在开始时间和结束时间里面!");
          }
        }
      });
    },

    // 分页器
    changeSize(size) {
      this.page.pageSize = size;
      this.getsportseventlist();
    },
    changePage(page) {
      this.page.pageNum = page;
      this.getsportseventlist();
    },
    // 终止赛事状态
    updataStatus(evt, row) {
      let target = evt.target;
      if (row.status == 0) {
        this.$alert("赛事未开始，不可操作", "", {
          confirmButtonText: "关闭",
        });
        return;
      }

      this.$confirm("是否确定终止赛事?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            matchId: row.matchId,
          };
          getterminationofrace(data).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: "终止赛事成功",
                type: "success",
              });
              this.getsportseventlist();
            } else {
              this.$message.error(res.message);
            }
          });
          if (target.nodeName == "SPAN") {
            target = evt.target.parentNode;
          }
          target.blur();
        })
        .catch(() => {
          if (target.nodeName == "SPAN") {
            target = evt.target.parentNode;
          }
          target.blur();
          this.$message({
            type: "info",
            message: "取消终止赛事",
          });
        });
    },
    // 时间查询
    getTiem(val) {
      if (val) {
        this.form.matchBeginTime = val[0];
        this.form.matchEndTime = val[1];
      } else {
        this.form.matchBeginTime = "";
        this.form.matchEndTime = "";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
// ::v-deep .el-button {
//   width: 60px;
//   padding: 10px;
// }
::v-deep .el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled){
  box-shadow: none;
}
.bot {
  display: flex;
  justify-content: flex-end;
}

.top {
  display: flex;

  justify-content: space-between;
}
.tvs {
  display: flex;
  justify-content: space-between;
}

::v-deep .el-upload-list__item {
  display: none;
}
.seo {
  display: flex;
}

.topsss {
  display: flex;
  justify-content: space-between;
}
.seoo {
  margin-left: 9px;
}
.wenzi {
  font-size: 14px;
  font-weight: 700;
  color: #606266;
}
.el-radio-group {
  font-size: 1px;
}
::v-deep .el-dialog__body {
  padding: 0px 20px;
}
::v-deep .el-dialog {
  margin-top: 1vh !important;
}

::v-deep .el-radio-button__inner {
 border-left: 1px solid #DCDFE6;
border-radius: 2px 0 0 2px;
}
::v-deep .el-radio-button:last-child .el-radio-button__inner {
border-radius: 2px;
}
::v-deep .el-radio-button:first-child .el-radio-button__inner {
  border-radius: 2px;
}
</style>
